﻿using System;
using System.Collections.Generic;
using Finance.TodoSoft;

namespace Finance.Data.Entities
{
	public interface IDocument : IDocumentBase
	{
		IDocumentProduct NewProduct();
		IList<IDocumentProduct> Products { get; }
	}

	internal class Document : DocumentBase, IDocument
	{
		private readonly DocumentProductCollection _documentProductsCollections;
		private readonly TracedList<IDocumentProduct> _products;
		private bool _productsEvaluated;

		public Document(DataBaseObjectCollection parentCollection,
			IContractors contractors) : base(parentCollection, contractors)
		{
			_documentProductsCollections = new DocumentProductCollection(ParentCollection.DataBase, this);
			_products = new TracedList<IDocumentProduct>();
		}
		
		public IList<IDocumentProduct> Products
		{
			get
			{
				if (!_productsEvaluated && Id != Guid.Empty)
				{
					var documentProducts = new DocumentProductCollection(DataBase, this);
					documentProducts.GetDocumentProducts(_products);
					_productsEvaluated = true;
				}

				return _products;
			}
		}

		public IDocumentProduct NewProduct()
		{
			return  new DocumentProduct(_documentProductsCollections);
		}

		public override void Save()
		{
			base.Save();

			//Save products
			foreach (var product in Products)
			{
				_documentProductsCollections.Save(product);	
			}

			foreach (var removedProduct in _products.Removed)
			{
				_documentProductsCollections.Delete(removedProduct);
			}

			_products.Removed.Clear();
		}
	}
}
